package com.huika.dealontop.utils;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.homepage.utils.cartproductnumber.CartProductNumber;
import com.huika.dealontop.control.login.event.LoginEvent;
import com.huika.dealontop.control.login.event.LogoutEvent;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.support.http.ServerFlagError;
import com.huika.dealontop.support.http.ServerJsonUnParseError;
import com.huika.dealontop.views.ToastMsg;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import de.greenrobot.event.EventBus;

/**
 * @author zwy
 * @ClassName: LoginUtils
 * @说明: 登陆帮助类
 * @date 2015年6月15日 上午9:53:46
 */
public class LoginUtils {
    private Context context;
    private String pwd;
    private String userName;
    //是否第三方登录（1.是 0.否）
    private String isThirdToken = "0";
    //来源0注册，1 facebook,2Twitter (第三方登录有效)
    private String isThirdType = "0";
    //昵称(第三方登录有效)
    private String nickName = null;
    private String email;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getIsThirdType() {
        return isThirdType;
    }

    public void setIsThirdType(String isThirdType) {
        this.isThirdType = isThirdType;
    }

    public String getIsThirdToken() {
        return isThirdToken;
    }

    public void setIsThirdToken(String isThirdToken) {
        this.isThirdToken = isThirdToken;
    }

    public LoginUtils(Context context) {
        super();
        this.context = context;
    }

    /**
     * @说明:登陆
     * @author: zwy
     */
    public void login(String userName, String pwd) {
        loginNet(userName, MD5Security.getMd5_32_UP(pwd));
    }

    /**
     * @说明:自动登陆
     * @author: zwy
     */
    public void autoLogin() {
        String userName = PreferencesHelper.getString(PreferencesHelper.KEY_LOGIN_NAME);
        String pwd = PreferencesHelper.getString(PreferencesHelper.KEY_LOGIN_PWD);
       // String userId = PreferencesHelper.getString(PreferencesHelper.KEY_LOGINISTHRID_USERID);
        String nickName = PreferencesHelper.getString(PreferencesHelper.KEY_LOGINISTHRID_NICKNAME);
        if (userName != null && !TextUtils.isEmpty(userName) && pwd != null && !TextUtils.isEmpty(pwd)) {
            loginNet(userName, pwd);
           // this.userName = userId;
        }else if(userName != null && !TextUtils.isEmpty(userName) && nickName != null && !TextUtils.isEmpty(nickName)){
            this.nickName = nickName;
            loginNet(userName,"");
        }
    }

    /**
     * 第三方登錄
     */

    public void thirdLogin(String userName) {

        if (userName != null && !TextUtils.isEmpty(userName)) {
            loginNet(userName, "");
            //保存第三方登入需要的userId和nickName用来进行快速登入。
           // PreferencesHelper.setString(PreferencesHelper.KEY_LOGINISTHRID_USERID, userId);
            PreferencesHelper.setString(PreferencesHelper.KEY_LOGINISTHRID_NICKNAME, nickName);
        }
    }

    /**
     * @说明:判断是否登陆
     * @author: zwy
     */
    public static boolean isLogin() {
        return GlobalApp.getInstance().getUserModel() == null ? false : true;
    }

    /**
     * @说明:
     * @author: zwy
     */
    public void logout() {
        GlobalApp.getInstance().setUserModel(null);
        PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_PWD, "");
        EventBus.getDefault().post(new LogoutEvent(1));
    }

    private void loginNet(String userName, String pwd) {
        this.userName = userName;
        this.pwd = pwd;
        //    /Member/MemberLoginValidate
        FormResultRequest<UserModel> request = new FormResultRequest<UserModel>(UrlConstants.LOGINVALIDATEFORUSERAPP, listener, errorListener,
                new TypeToken<RequestResult<UserModel>>() {
                }.getType());
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        //账号
        ajaxParams.putStringTypeParam("account", userName);
        //密码
        ajaxParams.putStringTypeParam("passWord", pwd);
        //1-网站 2-android 3-ios
        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);
        //1：中文，2：英文,3:泰文
        ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));
        if (!TextUtils.isEmpty(nickName)) {
            //是否第三方登录（1.是 0.否）
            ajaxParams.putStringTypeParam("isThirdLogin", "1");
            //来源0注册，1 facebook,2Twitter (第三方登录有效)
            ajaxParams.putStringTypeParam("sourceType", "1");
        }else{
            //是否第三方登录（1.是 0.否）
            ajaxParams.putStringTypeParam("isThirdLogin", "0");
            //来源0注册，1 facebook,2Twitter (第三方登录有效)
            ajaxParams.putStringTypeParam("sourceType", "0");
        }

        //昵称(第三方登录有效)
        ajaxParams.putStringTypeParam("nickName", nickName);

        request.setRequestParams(ajaxParams);
        VolleyRequestManager.addRequest(request, this);

    }

    private Listener<RequestResult<UserModel>> listener = new Listener<RequestResult<UserModel>>() {
        @Override
        public void onResponse(RequestResult<UserModel> arg0) {
            UserModel userModel = arg0.getRs();
            if (arg0.flag == 1 && userModel != null) {
                GlobalApp.getInstance().setUserModel(userModel);
                userModel.setEmail(email);

                if (!"1".equals(isThirdToken)) {
                    userModel.setIsThird(0);
                } else {
                    userModel.setIsThird(1);
                }
                PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_NAME, userName);
                PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_PWD, pwd);
                //ToastMsg.showToastMsg(context, arg0.msg + GlobalApp.getInstance().getUserId());
                EventBus.getDefault().post(new LoginEvent(1, arg0.msg));
                //登入成功后加载用户车资料
                new CartProductNumber(context,userModel.getUserID()+"");
            } else {
                //ToastMsg.showToastMsg(context, arg0.msg);
            }
        }
    };


    private ErrorListener errorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            String msg = UIUtils.getString(R.string.error_response);
            if (error instanceof ServerFlagError) {
                msg = ((ServerFlagError) error).result.msg;
            } else if (error instanceof ServerJsonUnParseError) {
                try {
                    String res = ((ServerJsonUnParseError) error).result;
                    JSONObject jsonObject = new JSONObject(res);
                    msg = jsonObject.getString("msg");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    if (error.networkResponse != null
                            && error.networkResponse.data != null) {
                        msg = new String(error.networkResponse.data, "utf-8");
                        if (TextUtils.isEmpty(msg)) {
                            msg = "未知异常";
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            ToastMsg.showToastMsg(context, msg == null || TextUtils.isEmpty(msg) ? UIUtils.getString(R.string.error_response) : msg);
            EventBus.getDefault().post(new LoginEvent(0, msg));
        }
    };

    public void setEmail(String email) {
        this.email = email;
    }
}
